<template>
  <div class="reservation-container">
    <div class="reservation-info">
      <div class="info-row">
        <span class="info-label">培训班编号：</span>
        <span class="info-value">{{ trainingClassCode || '-' }}</span>
        <span class="info-label">培训班名称：</span>
        <span class="info-value">{{ reservationInfo.className || '-' }}</span>
      </div>
      <!-- <div class="info-row">
        <span class="info-label">培训内容：</span>
        <span class="info-value">{{ reservationInfo.trainingContent || '-' }}</span>
      </div> -->
      <div class="info-row">
        <span class="info-label">开始时间：</span>
        <span class="info-value">{{ reservationInfo.startTime || '-' }}</span>
        <span class="info-label">结束时间：</span>
        <span class="info-value">{{ reservationInfo.endTime || '-' }}</span>
        <span class="info-label">培训地址：</span>
        <span class="info-value">{{ reservationInfo.address || '-' }}</span>
      </div>
      <div class="info-row">
        <!-- <span class="info-label">人数限制：</span>
        <span class="info-value">{{ reservationInfo.peopleLimit || '-' }}</span> -->
        <span class="info-label">当前预约人数：</span>
        <span class="info-value">{{ reservedStudents.length }}</span>
        <span class="info-label" v-if="reservationInfo.peopleLimit">剩余名额：</span>
        <span class="info-value" v-if="reservationInfo.peopleLimit" :class="remainingQuotaClass">
          {{ Math.max(0, reservationInfo.peopleLimit - reservedStudents.length) }}
        </span>
      </div>
    </div>

    <div class="students-container">
      <div class="students-panel">
        <div class="panel-header">
          <h3 class="panel-title">预约学员</h3>
          <el-button
            type="text"
            @click="batchRemoveReservation"
            class="batch-btn"
            :disabled="!selectedReservedStudents.length"
          >
            批量移出
          </el-button>
        </div>
        <el-table
          ref="reservedTable"
          :data="reservedStudents"
          border
          style="width: 100%;"
          @selection-change="handleReservedSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="name" label="姓名" width="150"></el-table-column>
          <el-table-column prop="projectName" label="项目" width="200"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                type="text"
                @click="handleRemoveReservation(scope.row)"
              >
                移出
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="students-panel">
        <div class="panel-header">
          <h3 class="panel-title">未预约学员</h3>
          <el-button
            type="text"
            @click="batchAddReservation"
            class="batch-btn"
            :disabled="!selectedUnreservedStudents.length || (reservationInfo.peopleLimit && reservedStudents.length >= reservationInfo.peopleLimit)"
          >
            批量预约
          </el-button>
        </div>
        <el-table
          ref="unreservedTable"
          :data="unreservedStudents"
          border
          style="width: 100%;"
          @selection-change="handleUnreservedSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="name" label="姓名" width="150"></el-table-column>
          <el-table-column prop="projectName" label="项目" width="200"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                type="text"
                @click="handleAddReservation(scope.row)"
                :disabled=" reservationInfo.peopleLimit !==null && reservationInfo.peopleLimit > 0 && reservedStudents.length >= reservationInfo.peopleLimit"
              >
                预约
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { selectClassStudentAppointmentStatus, editAppointmentStatus, addPractice } from '@/api/training/practiceClassStudent.js';
import {
  trainingClassList,getTrainingClass
} from "@/api/training/TrainingClass";
export default {
  name: 'ReservationList',
  props: {
    trainingClassId: {
      type: String,
      required: true
    },
    practiceAppointmentId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      // 预约信息
      reservationInfo: {},
      trainingClassCode: '',
      className: '',

      // 学员数据
      reservedStudents: [],
      unreservedStudents: [],
      selectedReservedStudents: [],
      selectedUnreservedStudents: []
    };
  },
  computed: {
    remainingQuotaClass() {
      const remaining = this.reservationInfo.peopleLimit - this.reservedStudents.length;
      return remaining <= 0 ? 'remaining-quota-warning' : '';
    }
  },
  watch: {
    trainingClassId: {
      immediate: true,
      handler() {
        this.loadReservationData();
      }
    },
    practiceAppointmentId: {
      immediate: true,
      handler() {
        this.loadReservationData();
      }
    }
  },
  methods: {
    async loadReservationData() {
      if (!this.trainingClassId || !this.practiceAppointmentId) return;

      try {
        const res = await selectClassStudentAppointmentStatus({
          practiceAppointmentId: this.practiceAppointmentId,
          trainingClassId: this.trainingClassId
        });
        const classRes = await getTrainingClass(this.trainingClassId);
        console.log(classRes)

        // 假设接口返回中包含培训班基本信息
        this.trainingClassCode = classRes.data.trainingClassCode || '';
        this.className = classRes.data.trainingClassName || '';

        // 处理预约信息
        this.reservationInfo = {
          className: this.className,
          // trainingContent: classRes.data.remarks || '',
          startTime: classRes.data.startDate || '',
          endTime: classRes.data.endDate || '',
          address: classRes.data.trainingAddress || '',
          peopleLimit: res.peopleLimit || 0
        };

        // 处理学员数据
        this.reservedStudents = (res.appointedStudents || []).map(student => ({
          id: student.studentId,
          name: student.studentName || '-',
          phone: student.phone || '-',
          projectName: student.projectName || '-',
          rawData: student,
          practiceAppointmentId: this.practiceAppointmentId,
          trainingClassId: this.trainingClassId
        }));

        this.unreservedStudents = (res.unappointedStudents || []).map(student => ({
          id: student.studentId,
          name: student.studentName || '-',
          phone: student.phone || '-',
          projectName: student.projectName || '-',
          rawData: student,
          practiceAppointmentId: this.practiceAppointmentId,
          trainingClassId: this.trainingClassId
        }));

      } catch (error) {
        console.error("获取预约名单失败：", error);
        this.$message.error("获取预约名单失败，请稍后重试");
      }
    },

    handleReservedSelectionChange(val) {
      this.selectedReservedStudents = val;
    },

    handleUnreservedSelectionChange(val) {
      this.selectedUnreservedStudents = val;
    },

    async batchRemoveReservation() {
      if (this.selectedReservedStudents.length === 0) {
        this.$message.warning("请先选中要移出的预约学员");
        return;
      }

      try {
        const removeIds = this.selectedReservedStudents.map(
          (item) => item.rawData.practiceClassStudentId
        );
        await editAppointmentStatus(removeIds);

        this.unreservedStudents = [
          ...this.unreservedStudents,
          ...this.selectedReservedStudents
        ];
        this.reservedStudents = this.reservedStudents.filter(
          (item) => !removeIds.includes(item.rawData.practiceClassStudentId)
        );

        this.$refs.reservedTable.clearSelection();
        this.selectedReservedStudents = [];
        this.$message.success("批量移出成功");
      } catch (error) {
        console.error("批量移出失败：", error);
        this.$message.error("批量移出失败，请稍后重试");
      }
    },

    async batchAddReservation() {
      if (this.selectedUnreservedStudents.length === 0) {
        this.$message.warning("请先选中要预约的学员");
        return;
      }

      const remainingQuota = this.reservationInfo.peopleLimit - this.reservedStudents.length;
      if (this.selectedUnreservedStudents.length > remainingQuota) {
        this.$message.warning(`剩余可预约名额为${remainingQuota}，请减少选中人数`);
        return;
      }

      try {
        const addList = this.selectedUnreservedStudents.map((item) => ({
          practiceAppointmentId: item.practiceAppointmentId,
          trainingClassId: item.trainingClassId,
          studentId: item.rawData.studentId,
          projectId: item.rawData.projectId,
        }));
        await addPractice(addList);

        this.reservedStudents = [
          ...this.reservedStudents,
          ...this.selectedUnreservedStudents
        ];
        const addedIds = this.selectedUnreservedStudents.map((item) => item.id);
        this.unreservedStudents = this.unreservedStudents.filter(
          (item) => !addedIds.includes(item.id)
        );

        this.$refs.unreservedTable.clearSelection();
        this.selectedUnreservedStudents = [];
        this.$message.success("批量预约成功");
      } catch (error) {
        console.error("批量预约失败：", error);
        this.$message.error("批量预约失败，请稍后重试");
      }
    },

    async handleRemoveReservation(row) {
      try {
        const index = this.reservedStudents.findIndex(item => item.id === row.id);
        if (index !== -1) {
          const removed = this.reservedStudents.splice(index, 1)[0];
          this.unreservedStudents.push(removed);

          await editAppointmentStatus([row.rawData.practiceClassStudentId]);

          this.$refs.reservedTable.clearSelection();
          this.selectedReservedStudents = [];
          this.$message.success("移出成功");
        }
      } catch (error) {
        console.error("移出失败：", error);
        this.$message.error("移出失败，请稍后重试");
      }
    },

    async handleAddReservation(row) {
      if (this.reservationInfo.peopleLimit && this.reservedStudents.length >= this.reservationInfo.peopleLimit) {
        this.$message.warning(`已达最大预约人数(${this.reservationInfo.peopleLimit})`);
        return;
      }

      try {
        const index = this.unreservedStudents.findIndex(item => item.id === row.id);
        if (index !== -1) {
          const added = this.unreservedStudents.splice(index, 1)[0];
          this.reservedStudents.push(added);

          await addPractice([{
            practiceAppointmentId: row.practiceAppointmentId,
            trainingClassId: row.trainingClassId,
            studentId: row.rawData.studentId,
            projectId: row.rawData.projectId
          }]);

          this.$refs.unreservedTable.clearSelection();
          this.selectedUnreservedStudents = [];
          this.$message.success("预约成功");
        }
      } catch (error) {
        console.error("预约失败：", error);
        this.$message.error("预约失败，请稍后重试");
      }
    }
  }
};
</script>

<style scoped>
.reservation-container {
  margin: 20px 0;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.reservation-info {
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.info-label {
  font-weight: 500;
  margin-right: 8px;
  color: #666;
  min-width: 80px;
}

.info-value {
  margin-right: 20px;
  margin-bottom: 5px;
  color: #333;
}

.remaining-quota-warning {
  color: #f56c6c;
  font-weight: 500;
}

.students-container {
  display: flex;
  gap: 20px;
}

.students-panel {
  flex: 1;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.panel-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.batch-btn {
  color: #409eff;
  padding: 4px 0;
}

.batch-btn:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.batch-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
  text-decoration: none;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
  border-radius: 4px;
  overflow: hidden;
}

.el-table__header {
  background-color: #f5f7fa !important;
}

.el-table__header th {
  font-weight: 500 !important;
  color: #303133 !important;
  border-bottom: 1px solid #e6e8eb !important;
}

.el-table__body tr {
  height: 50px !important;
}

.el-table__body td {
  padding: 12px 8px !important;
  color: #606266 !important;
  border-bottom: 1px solid #f0f2f5 !important;
}

.el-table__body tr:hover > td {
  background-color: #f9fafc !important;
}

.el-table__body tr.current-row > td {
  background-color: #eef5ff !important;
  border-left: 2px solid #409eff !important;
}

.el-table--border th,
.el-table--border td {
  border-right: 1px solid #f0f2f5 !important;
}

.el-table--border::after,
.el-table--group::after,
.el-table td.gutter:last-of-type {
  background-color: #f0f2f5 !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .students-container {
    flex-direction: column;
  }
}

.students-container {
  display: flex;
  gap: 20px;
  height: 500px;
}

.students-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.students-panel .el-table {
  flex: 1;
  overflow: auto;
}

.students-panel .el-table__body-wrapper {
  max-height: 400px;
  overflow-y: auto;
}
</style>
